var express = require('express')
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
const text_lines = require('./text.js');

// Express is using the 'public' folder (for accessing style.css)
app.use(express.static('public'));

// Declare which port server is listening too
server.listen(3000);
console.log('Server started at',3000);

const game_socket_map = {}

io.sockets.on('connection' , clientConnected);

let connect_cnt = 0

function clientConnected (socket) {
  // New connected user
  socket.nickname = '';   // Not 'logged in' yet , not nickname associated
  console.log('Client  ' + socket.handshake.address + '  connected.');

  connect_cnt++
  updateLimit()

  // Client disconnected
  socket.on('disconnect' , function () {
    const socket_id = socket.id
    console.log('Client  ' + socket.handshake.address + '  disconnected.',socket_id);

    connect_cnt--
    updateLimit()

    if (socket.is_game) {
      console.log("===========game end",socket_id);
      if (game_socket_map[socket_id]) {
        console.log("delete game_socket_map");
        delete game_socket_map[socket_id]
      }
    }

    // Remove the user that disconnected, if it was 'logged in'
    if (socket.nickname !== '') {
      // Notify the other Users
      socket.broadcast.emit('system message' , '<b>' + socket.nickname + '</b> 离开了.');
    }
  });

  // Broadcast the message to all clients
  socket.on('send message' , (message) => {
    console.log("user send",message);
    // Broadcast the message to all clients
    io.sockets.emit('message' , message);
    newLine(socket)
  });

  socket.on('chapter' , changeChapter);

  socket.on('error' , (e) => {
    console.log("on error");
    console.log(e);
  });

  socket.on('screen' , () => {
    socket.is_game = true
    game_socket_map[socket.id] = true
    console.log("==========game start===",socket.id);
  });

  // Client chose nickname
  socket.on('new client nickname', function (nickname) {
    // Add the new client to the sockets list
    socket.nickname = nickname;

    // Notify other clients only that this new clients has joined the chat-room
    socket.broadcast.emit('system message' , '<b>' + socket.nickname + '</b> 加入了游戏');

    newLine(socket)
  });
}

Number.prototype.clamp = function (min, max) {
  return Math.min(Math.max(this, min), max);
};

const auto_random_pos = () => {
  const p1 = Math.random()
  if (p1 > 0.8) {
    return Math.random() * 0.8 
  } else {
    return Math.random() * 0.4
  }
};

const auto_send = () => {
  const auto_message = {
    nickname : "键盘侠",
    content : text_lines.get_random_lines(),
    pos : auto_random_pos(),
  }
  auto_message.pos = Math.max(0.05, auto_message.pos)
  console.log(auto_message);
  for (let id in game_socket_map) {
    io.sockets.to(id).emit("message",auto_message)
  }
};

setInterval(auto_send,1200)

const updateLimit = () => {
  const cnt_per_second = 3
  let time_limit = connect_cnt * 1 / cnt_per_second  
  time_limit = time_limit.clamp(1,7) 
   
  console.log("connect_cnt %d time_limit %f",connect_cnt,time_limit);
  io.sockets.emit('timelimit' , {
    cnt : connect_cnt,
    limit : time_limit,
  });
};

function newLine (socket) {
  //const line = text_lines.get_random_lines()
  //socket.emit('newline' , line);
}

function changeChapter (new_chapter) {
  const fix_chapter = text_lines.changeChapter(new_chapter)
  io.sockets.emit("changeChapter",fix_chapter)
}


